package middle.ground.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;

public class AESUtil{

	private static final String UTF8 = "UTF-8";

	public static String encrypt(String content, String keyStr) {
		try {
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(1, generateKey(keyStr));
			return Base64.encode(cipher.doFinal(content.getBytes(UTF8)));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String decrypt(String content, String keyStr) {
		try {
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(2, generateKey(keyStr));
			return new String(cipher.doFinal(Base64.decode(content)), UTF8);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static Key generateKey(String key) throws Exception {
		try {
			return new SecretKeySpec(key.getBytes(), "AES");
		} catch (Exception e) {
			throw e;
		}
	}

}
